﻿using System;
using System.Windows.Forms;
using ProjectAutumn.Window;

namespace ProjectAutumn.WindowSystem.FormsWindow
{
    class FormWindowDevice : WindowDevice
    {
        private readonly Form mainForm;
        public FormWindowDevice(Game game)
                : base(game)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            mainForm = new ChildForm();
        }
        public override IntPtr Handle
        {
            get { return mainForm.Handle; }
        }
        protected override void ApplyChanges(int width, int height, bool fullscreen)
        {
            if (fullscreen) return;
            mainForm.Width = width;
            mainForm.Height = height;
        }
        public override int Width
        {
            get { return mainForm.Width; }
        }
        public override int Height
        {
            get { return mainForm.Height; }
        }
        public override void SetTitle(string value)
        {
            mainForm.Text = value;
        }
        public override void Run()
        {
            if (Utility.IsWindows())
                Application.Idle += ApplicationIdleWindows;
            else
                Application.Idle += ApplicationIdle;
            Application.Run(mainForm);
        }
        public override void GlFlip()
        {
            throw new NotImplementedException("Form doesn't yet support OpenGL");
        }
        public override WindowCapabilities WindowCapabilities
        {
            get
            {
                return new WindowCapabilities
                {
                        SupportsChangeTitle = true,
                        SupportsGLFlip = false,
                };
            }
        }
        private void ApplicationIdle(object sender, EventArgs e) { Game.Tick(); }
        private void ApplicationIdleWindows(object sender, EventArgs e)
        {
            NativeMessage message;
            while (!NativeMethods.PeekMessage(out message, IntPtr.Zero, 0, 0, 0))
            {
                if (Game.IsExiting) return;
                Game.Tick();
            }
        }
    }
}
